<template>
  <div class="container">
    <el-card>
      <p>纪承</p>
      <!-- 头部 -->
      <el-row>
        <el-col :span="16">
          <el-form class="active" :inline="true">
            <el-form-item label="关键字" style="margin-left: 20px">
              <el-input
                size="mini"
                placeholder="根据文章标题搜索"
                v-model="queryInfo.keyword"
              ></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="queryInfo.state"
                placeholder="请选择"
                size="mini"
              >
                <el-option
                  v-for="item in stateList"
                  :key="item.id"
                  :label="item.state"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="margin-right: 150px">
              <el-button size="mini" @click="clearData">清除</el-button>
              <el-button size="mini" type="primary" @click="getArticleList"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8" style="text-align: right">
          <el-button
            size="small"
            type="success"
            class="el-icon-edit"
            @click="articleDialogVisible = true"
            >新增技巧</el-button
          >
        </el-col>
      </el-row>
      <!-- 消息提示 -->
      <el-alert
        :title="`数据一共 ${total} 条`"
        type="info"
        show-icon
        :closable="false"
        style="margin-bottom: 10px"
      >
      </el-alert>
      <!-- 表格 -->
      <el-table :data="articleList" style="width: 100%">
        <el-table-column type="index" label="序号" width="70">
        </el-table-column>
        <el-table-column label="文章标题" width="400">
          <template slot-scope="{ row }">
            {{ row.title }}
            <i
              @click="onClick"
              class="el-icon-film"
              v-if="row.videoURL !== null"
              style="color: blue; position: relative"
            >
            </i>
          </template>
        </el-table-column>
        <el-table-column prop="visits" label="阅读数" width="120">
        </el-table-column>
        <el-table-column
          label="录入人"
          prop="username"
          width="100"
        ></el-table-column>
        <el-table-column prop="createTime" label="录入时间" width="200">
          <template slot-scope="{ row }">{{
            row.createTime | parseTime
          }}</template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template slot-scope="{ row }">
            <div v-if="row.state === 1">已启用</div>
            <div v-else>已禁用</div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button type="text" @click="detailsArticle(row)">预览</el-button
            ><el-button
              v-if="row.state === 0"
              type="text"
              @click="checkStateEnable(row.id, 1)"
              >启用</el-button
            >
            <el-button v-else type="text" @click="checkStateDisable(row.id, 0)"
              >禁用</el-button
            ><el-button
              :disabled="row.state === 1 ? true : false"
              type="text"
              @click="editArticle(row)"
              >修改</el-button
            ><el-button
              :disabled="row.state === 1 ? true : false"
              type="text"
              @click="deleteArticle(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </el-card>
    <!-- 新增技巧弹框 -->
    <el-dialog
      @close="onCloses"
      :visible.sync="articleDialogVisible"
      width="55%"
      title="新增技巧"
    >
      <span>
        <el-form
          ref="addArticleForm"
          :model="addArticleForm"
          label-width="80px"
          :rules="addArticleFormRules"
        >
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="addArticleForm.title"></el-input>
          </el-form-item>
          <el-form-item label="文章内容" prop="articleBody">
            <quill-editor
              ref="myQuillEditor"
              v-model="addArticleForm.articleBody"
              :options="editorOption"
            >
            </quill-editor>
          </el-form-item>
          <el-form-item label="视频地址">
            <el-input v-model="addArticleForm.videoURL"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="articleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addArticle">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改技巧弹框 -->
    <el-dialog
      title="修改文章"
      :visible.sync="editArticleDialogVisible"
      width="55%"
    >
      <span>
        <el-form
          ref="addArticleForm"
          :model="addArticleForm"
          label-width="80px"
          :rules="addArticleFormRules"
        >
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="addArticleForm.title"></el-input>
          </el-form-item>
          <el-form-item label="文章内容" prop="articleBody">
            <quill-editor
              v-model="addArticleForm.articleBody"
              ref="myQuillEditor"
              :options="editorOption"
            ></quill-editor>
          </el-form-item>
          <el-form-item label="视频地址">
            <el-input v-model="addArticleForm.videoURL"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editArticleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editorArticle">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 预览弹框 -->
    <el-dialog title="预览文章" :visible.sync="showDialogVisible" width="55%">
      <span>
        <div class="title">
          <h2>{{ showArticleList.title }}</h2>
          <div>
            <span>{{ showArticleList.createTime | parseTime }}</span>
            <span>{{ showArticleList.username }}</span>
            <span class="el-icon-view"></span>
            <span>{{ showArticleList.visits }}</span>
          </div>
        </div>
        <div class="content">
          <p v-html="showArticleList.articleBody"></p>
        </div>
      </span>
    </el-dialog>
    <video v-if="videos" width="320" height="240" controls class="video">
      <source :src="addArticleForm.videoURL" type="video/mp4" />
    </video>
  </div>
</template>

<script>
import {
  list as articleList,
  add as articleAdd,
  remove as articleRemove,
  changeState,
  update,
  detail
} from '../../api/hmmm/articles'
// 代码块高亮
import hljs from 'highlight.js'
import 'highlight.js/styles/xcode.css'

export default {
  data () {
    return {
      // 富文本编辑器修改
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // toggled buttons
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote', 'code-block'],
            ['image', 'link']
          ],
          // 代码块高亮
          syntax: {
            highlight: text => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            }
          }
        }
      },
      addArticleFormRules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      },
      addArticleForm: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      articleList: [],
      total: 0,
      queryInfo: {
        keyword: null,
        page: 1,
        pagesize: 20,
        state: null
      },
      stateList: [
        { id: 1, state: '启用' },
        { id: 0, state: '禁用' }
      ],
      articleDialogVisible: false,
      editArticleDialogVisible: false,
      showDialogVisible: false,
      showArticleList: {},
      flag: true,
      videos: false
    }
  },

  created () {
    this.getArticleList()
  },

  methods: {
    onClose () {
      this.$refs.addArticleForm.resetFields()
      this.articleDialogVisible = false
    },
    onClick () {
      this.videos = !this.videos
    },

    // 获取列表数据
    async getArticleList () {
      try {
        const articleRes = await articleList(this.queryInfo)
        console.log(articleRes)

        this.articleList = articleRes.data.items
        this.total = articleRes.data.counts
        // this.$message.success('获取成功')
      } catch (err) {
        this.$message.error('获取失败')
      }
    },
    // 改变每页条数
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getArticleList()
    },
    // 切换当前页
    handleCurrentChange (val) {
      this.queryInfo.page = val
      this.getArticleList()
    },
    // 点击清空按钮清空数据
    clearData () {
      this.queryInfo.state = null
      this.queryInfo.keyword = null
      this.getArticleList()
    },
    // 新增文章
    async addArticle () {
      try {
        await this.$refs.addArticleForm.validate()
        await articleAdd(this.addArticleForm)
        this.$message.success('操作成功')
        this.articleDialogVisible = false
        this.addArticleForm.title = ''
        this.addArticleForm.articleBody = ''
        this.addArticleForm.videoURL = ''

        // this.onCloses()
        this.getArticleList()
        // this.$refs.addArticleForm.resetFields()
      } catch (err) {
        this.$message.error('操作失败')
      }
    },

    // 删除文章
    deleteArticle (row) {
      this.$confirm('是否删除该条数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            await articleRemove(row)

            const index = this.articleList.findIndex(item => {
              return row.id === item.id
            })
            console.log(index)
            this.articleList = this.articleList.splice(index, 1)
            this.$message.success('删除成功！')
            this.getArticleList()
          } catch (err) {
            return this.$message.error('删除失败！')
          }
        })
        .catch(() => {
          this.$message('已取消删除')
        })
    },
    // 切换文章状态
    // 点击启用
    async checkStateEnable (id, state) {
      try {
        const res = await changeState({ id, state })
        console.log(res)

        this.getArticleList()
      } catch (err) {
        return this.$message.error('修改状态失败！')
      }
    },
    // 点击禁用
    // 修改文章取数据
    async checkStateDisable (id, state) {
      try {
        const res = await changeState({ id, state })
        console.log(res)

        this.getArticleList()
      } catch (err) {
        return this.$message.error('修改状态失败！')
      }
    },
    async editArticle (row) {
      this.addArticleForm.title = row.title
      this.addArticleForm.articleBody = row.articleBody
      this.addArticleForm.videoURL = row.videoURL
      this.addArticleForm.id = row.id
      this.editArticleDialogVisible = true
    },
    // 修改文章请求
    editorArticle () {
      this.$refs.addArticleForm.validate(async flag => {
        if (!flag) {
          return this.$message.error('请填写必填项！')
        }
        try {
          await this.$refs.addArticleForm.validate()
          await update(this.addArticleForm)
          this.$message.success('修改文章成功！')
          this.editArticleDialogVisible = false
          this.$refs.addArticleForm.resetFields()
          this.addArticleForm.title = ''
          this.addArticleForm.articleBody = ''
          this.addArticleForm.videoURL = ''
          this.getArticleList()
        } catch (err) {
          return this.$message.error('修改文章失败！')
        }
      })
    },
    // 点击预览文章按钮
    async detailsArticle (row) {
      try {
        this.showDialogVisible = true
        const res = await detail(row)
        this.showArticleList = res.data
        this.showArticleList.username = row.username
      } catch (err) {
        return this.$message.error('获取文章详情失败！')
      }
    },
    onCloses () {
      this.articleDialogVisible = false
      this.$refs.addArticleForm.resetFields()
    }
  }
}
</script>

<style scoped lang='less'>
.container {
  padding: 10px;
}
.active {
  display: flex;
  justify-content: space-between;
}
/deep/.ql-container {
  height: 200px;
}
.title {
  h2 {
    font-size: 21px;
  }
  span {
    margin-left: 10px;
  }
}
.content {
  background: #f5f5f5;
  padding: 10px;
  margin-top: 10px;
  border-top: 1px dashed #ccc;
}
.el-icon-film {
  cursor: pointer;
  font-size: 18px;
}
video {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 800px;
  height: 600px;
}
.demo {
  display: inline-block;
  width: 600px;
  height: 338px;
  text-align: center;
  line-height: 100px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}

.demo:hover {
  display: block;
}
</style>
